package com.xbao.open.impl;

import com.xbao.core.component.page.Pagination;
import com.xbao.core.util.MyBeanUtil;
import com.xbao.model.open.OpenContent;
import com.xbao.model.open.OpenContentDoc;
import com.xbao.model.open.OpenContentReq;
import com.xbao.model.open.OpenContentVo;
import com.xbao.model.vo.ClsVo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;

import java.util.List;

public class OpenServiceImpl implements com.xbao.open.OpenService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Pagination<OpenContentVo> searchContents(OpenContentReq req) {
        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        qb.minimumShouldMatch(40);
        qb.must(QueryBuilders.matchQuery("", ""));
        BoolQueryBuilder filter = QueryBuilders.boolQuery();
        if (req.getCategory() != null)
            filter.must(QueryBuilders.matchQuery("category", req.getCategory()));
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(qb)
                .withFilter(filter)
                .withPageable(null)
                .withSort(null)
                .build();
        Page<OpenContentDoc> sampleEntities =
                elasticsearchTemplate.queryForPage(searchQuery, OpenContentDoc.class);
        List<OpenContentVo> vos = MyBeanUtil.copyList(sampleEntities.getContent(), OpenContentVo.class);
        Pagination<OpenContentVo> page=new Pagination<>(req.getPageno(),req.getPagesize(),vos);
        return page;
    }
}
